const { query } = require("../../db/db");
const md5 = require("md5-node");
const svgCaptcha = require("svg-captcha"); //验证码插件
const tencentcloud = require("tencentcloud-sdk-nodejs");
// 导入对应产品模块的client models。
const smsClient = tencentcloud.sms.v20210111.Client;
//导入工具类
const util = require("../../util/util");

//用户API
let data;
let user = {};

// //腾讯云短信配置文件,这些在腾讯云控制台都能看见
const config = {
  secretId: "AKIDiKm089zcO7fz4JW1MVQ6XlogLmzzkEVY",
  secretKey: "75sTpytZ1EEzgHfrpa9VdXFj170fFj04",
  SmsSdkAppId: "1400735347",
  SignName: "前端小白公众号",
  TemplateId: "1537388",
  Time: 5,
};

//获得手机短信验证码
exports.getcode = async (req, res) => {
  try {
    const phone = req.body.phone;
    const code = Math.round(Math.random() * 899999 + 100000);
    console.log(phone, code);
    /* 实例化要请求产品(以sms为例)的client对象 */
    const client = new smsClient({
      credential: {
        secretId: config.secretId,
        secretKey: config.secretKey,
      },
      region: "ap-guangzhou",
      profile: {
        signMethod: "HmacSHA256",
        httpProfile: {
          reqMethod: "POST",
          reqTimeout: 30,
          endpoint: "sms.tencentcloudapi.com",
        },
      },
    });

    const params = {
      SmsSdkAppId: config.SmsSdkAppId,
      SignName: config.SignName,
      ExtendCode: "",
      SenderId: "",
      SessionContext: "",
      /* 下发手机号码，采用 e.164 标准，+[国家或地区码][手机号]
       * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
      PhoneNumberSet: [`+86${phone}`],
      TemplateId: config.TemplateId,
      /* 模板参数: 若无模板参数，则设置为空*/
      TemplateParamSet: [`${code}`, "10"],
    };

    // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
    client.SendSms(params, function (err, response) {
      // 请求异常返回，打印异常信息
      if (err) {
        let data = {
          code: 500,
          message: "发送失败，请稍后重试",
        };
        res.json(data);
      }
      // 请求正常返回
      //保存手机号验证码
      req.session.code = code;
      req.session.phone = phone;
      res.json({ status: 200, msg: code });
      // let data = {
      //   code: 200,
      //   message: "发送成功",
      // };
      // res.json(data);
    });
  } catch (error) {
    let data = {
      code: 500,
      message: "异常请求",
    };
    res.json(data);
  }
};

//获取数字字母验证码
exports.captcha = async (req, res) => {
  let captcha = svgCaptcha.create({
    size: 4, // size of random string
    ignoreChars: "0o1i", // filter out some characters like 0o1i
    noise: 3, // number of noise lines
    color: true, //, characters will have distinct colors instead of grey, true if background option is set
    background: "#fff", // background color of the svg image
  });
  //保存图形验证码文本
  req.session.captcha = captcha.text.toLowerCase();
  //返回验证码数据
  res.type("svg");
  res.status(200).send(captcha.data);
};

//用户登录
exports.login = async (req, res) => {
  let name = req.body.userName;
  let pwd = md5(req.body.password);
  let captcha = req.body.captcha;
  try {
    //判断验证码是否正确
    if (captcha.toLowerCase() !== req.session.captcha) {
      data = { error_code: 1, message: "验证码不正确" };
    } else {
      delete req.session.captcha;
      let sql = "SELECT * from user WHERE user_name =? LIMIT 1 ;";
      const result = await query(sql, [name]);
      if (result[0]) {
        if (result[0].password === pwd) {
          //保存用户id
          req.session.userId = result[0].user_id;
          res.cookie("user_id", result[0].user_id);
          data = { success_code: 200 };
        } else {
          data = { error_code: 1, message: "密码错误" };
        }
      } else {
        data = { error: 1, message: "用户不存在" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "查询用户失败" };
  }
  res.json(data);
};

//用户短信注册登录
exports.phoneLogin = async (req, res) => {
  let phone = req.body.phone;
  let phoneCode = req.body.phoneCode;

  console.log(phone, phoneCode);
  try {
    //判断手机验证码是否正确
    console.log(req.session.code);
    if (req.session.code != phoneCode) {
      data = { error_code: 1, message: "验证码错误" };
    } else {
      //用户存在
      let sql = "SELECT * from user WHERE phone = ? LIMIT 1 ;";
      const result = await query(sql, [phone]);

      if (result[0]) {
        req.session.userId = result[0].user_id;
        res.cookie("user_id", result[0].user_id);
        data = { success_code: 200, message: "登录成功" };
      } else {
        //用户不存在
        let sql =
          "INSERT INTO user(user_name,phone,avatar,password) VALUES(?,?,?,?)";
        let avatarSrc = "/images/avatar/monkey.png";
        const result = await query(sql, [phone, phone, avatarSrc, md5(123456)]);
        res.cookie("user_id", result.insertId);
        data = { success_code: 200, message: "注册成功" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "请求数据失败" };
  }
  res.json(data);
};

//获取用户信息
exports.getUserInfo = async (req, res) => {
  try {
    let { userId } = req.query;
    console.log(userId);
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        data = { success_code: 200, data: result[0] };
      } else {
        data = { error_code: 1, message: "用户信息不存在" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "获取用户信息失败" };
  }
  res.json(data);
};

//更新用户名
exports.updateUserName = async (req, res) => {
  try {
    let { userId, userName } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql = "UPDATE user SET user_name = ? WHERE user_id = ?;";
        const result = await query(sql, [userName, userId]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新用户名失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//更新用户性别
exports.updateUserSex = async (req, res) => {
  try {
    let { userId, sex } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql = "UPDATE user SET sex = ? WHERE user_id = ?;";
        const result = await query(sql, [sex, userId]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新性别失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//更新用户生日
exports.updateUserBirthday = async (req, res) => {
  try {
    let { userId, birthday } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql = "UPDATE user SET birthday = ? WHERE user_id = ?;";
        const result = await query(sql, [birthday, userId]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新生日失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//更新用户签名
exports.updateUserSign = async (req, res) => {
  try {
    let { userId, sign } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql = "UPDATE user SET sign = ? WHERE user_id = ?;";
        const result = await query(sql, [sign, userId]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新个签失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//更新用户头像
exports.updateUserAvatar = async (req, res) => {
  try {
    let { userId, avatar } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql2 = "UPDATE user SET avatar = ? WHERE user_id = ?;";
        const result2 = await query(sql2, [avatar, userId]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新个签失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//更新用户信息
exports.updateUserInfo = async (req, res) => {
  try {
    let { userId, userName, avatar, password, sex, sign, birthday } = req.body;
    if (userId) {
      let sql = "SELECT * from user WHERE user_id = ? LIMIT 1;";
      const result = await query(sql, [userId]);
      if (result[0]) {
        //更新数据库
        let sql =
          "UPDATE user SET user_name = ?,avatar = ?,password = ?,sex = ? ,birthday = ?,sign = ?WHERE user_id = ?;";
        const result = await query(sql, [
          userName,
          avatar,
          password,
          sex,
          birthday,
          sign,
          userId,
        ]);
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新用户信息失败" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "该用户不存在" };
  }
  res.json(data);
};

//用户评论部分

//获取当前用户评论
exports.getUserComment = async (req, res) => {
  try {
    let { userId, movieId } = req.query;
    if (userId) {
      let sql =
        "SELECT * FROM comment WHERE user_id = ? AND movie_id= ? LIMIT 1;";
      const result = await query(sql, [userId, movieId]);
      if (result[0]) {
        data = { success_code: 200, data: result[0] };
      } else {
        data = { error_code: 1, message: "用户未评论" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "error" };
  }
  res.json(data);
};

//获取所有用户通过审核的评论
exports.getAllUserPassComment = async (req, res) => {
  try {
    let { movieId } = req.query;
    if (movieId) {
      let sql =
        "SELECT * FROM user INNER JOIN comment ON user.user_id = comment.user_id WHERE comment.movie_id = ? AND comment.is_pass = ? ;";
      const result = await query(sql, [movieId, 1]);
      if (result[0]) {
        data = { success_code: 200, data: result[0] };
      } else {
        data = { error_code: 1, message: "未评论" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "error" };
  }
  res.json(data);
};

//更新用户评论
exports.updateUserComment = async (req, res) => {
  let { userId, movieId, score, commentContent, commentDate } = req.body;
  console.log(userId, movieId);
  if (userId) {
    let sql = "SELECT comment_id from comment WHERE user_id = ?";
    const result = await query(sql, [userId]);

    if (result.length !== 0) {
      //评论存在
      let sql2 =
        "UPDATE comment SET user_score = ?, comment_content = ?, comment_date = ?,support_num = ?,is_pass = ?,support_user = ? WHERE comment_id = ? ;";
      const result2 = await query(sql2, [
        score,
        commentContent,
        commentDate,
        0,
        0,
        undefined,
        result[0].comment_id,
      ]);
      console.log(result2[0]);
      if (result[0]) {
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新评论失败" };
      }
    } else {
      //评论不存在
      let sql3 =
        "INSERT INTO comment(user_id,movie_id,user_score,comment_content,comment_date,support_num,is_pass) VALUES(?,?,?,?,?,?,?);";
      const result = await query(sql3, [
        userId,
        movieId,
        score,
        commentContent,
        commentDate,
        0,
        0,
      ]);
      if (result3[0]) {
        data = { success_code: 200 };
      } else {
        data = { error_code: 1, message: "更新评论失败" };
      }
    }
  }
  res.json(data);
};

//获取当前评论
exports.getCommentByID = async (req, res) => {
  try {
    let { commentId } = req.query;
    if (commentId) {
      let sql = "SELECT * FROM comment WHERE comment_id = ? LIMIT 1;";
      const result = await query(sql, [commentId]);
      if (result[0]) {
        data = { success_code: 200, data: result[0] };
      } else {
        data = { error_code: 1, message: "用户未评论" };
      }
    }
  } catch (error) {
    data = { error_code: 1, message: "error" };
  }
  res.json(data);
};

//更新当前评论的用户点赞
exports.updateUserSupport = async (req, res) => {
  try {
    let { commentId, supportNum, supportUser } = req.body;
    let sqlStr =
      "UPDATE comment SET support_num = ? , support_user = ? WHERE comment_id = ?;";
    const result = await query(sqlStr, [supportNum, supportUser, commentId]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "操作失败" });
    } else {
      res.json({ success_code: 200 });
    }
  } catch (error) {}
};

//用户下单
exports.order = async (req, res) => {
  try {
    let {
      userId,
      scheduleId,
      orderPhone,
      orderDate,
      ticketNum,
      totalPrice,
      orderSeatInfo,
      payType,
    } = req.body;
    let phoneCode = util.randomCode(6);
    let sqlStr =
      "INSERT INTO orders(user_id,schedule_id,order_phone,order_date,ticket_num,ticket_total_price,order_seat_info,pay_type,phone_code) VALUES(?,?,?,?,?,?,?,?,?); ";
    const result = await query(sqlStr, [
      userId,
      scheduleId,
      orderPhone,
      orderDate,
      ticketNum,
      totalPrice,
      orderSeatInfo,
      payType,
      phoneCode,
    ]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "操作失败" });
    } else {
      res.json({ success_code: 200, data: { phone_code: phoneCode } });
    }
  } catch (error) {}
};

//获取个人订单信息
exports.getOrderByUserId = async (req, res) => {
  try {
    let { userId } = req.query;
    let sqlStr =
      "SELECT * FROM orders INNER JOIN schedule ON orders.schedule_id = schedule.schedule_id INNER JOIN movie ON movie.movie_id = schedule.movie_id INNER JOIN cinema ON cinema.cinema_id = schedule.cinema_id WHERE user_id = ?;";
    const result = await query(sqlStr, [userId]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "未找到数据" });
    } else {
      res.json({ success_code: 200, data: result });
    }
  } catch (error) {}
};

//加载影院列表
exports.getCinemaList = async (req, res) => {
  let sql =
    "SELECT * FROM schedule INNER JOIN cinema ON schedule.cinema_id = cinema.cinema_id INNER JOIN movie ON schedule.movie_id = movie.movie_id;";
  const result = await query(sql);

  result2 = result.filter(value => {
    return new Date(value.show_date + "," + value.show_time) - new Date() > 0;
  });
  for (let i = 0; i < result2.length; i++) {
    for (let j = i + 1; j < result2.length; j++) {
      if (result2[i]["cinema_id"] === result2[j]["cinema_id"]) {
        result2.splice(j, 1);
        j = j - 1;
      }
    }
  }
  res.json({ success_code: 200, data: result2 });
};

//加载当前影院详细信息
exports.getCurrentCinemaDetail = async (req, res) => {
  try {
    let cinemaId = req.query.cinemaId;
    let sqlStr = "SELECT * FROM cinema WHERE cinema_id = ? LIMIT 1;";
    const result = await query(sqlStr, [cinemaId]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "获取当前影院信息失败" });
    } else {
      res.json({ success_code: 200, data: result[0] });
    }
  } catch (error) {
    res.json({ error_code: 1, message: "影院不存在" });
  }
};

//加载当前影院排片
exports.getCurrentCinemaMovieSchedule = async (req, res) => {
  try {
    let cinemaId = req.query.cinemaId;
    let sql = "SELECT * FROM schedule WHERE cinema_id = ?;";
    const result = await query(sql, [cinemaId]);

    let tempMovieArr = [];
    result.forEach(value => {
      if (new Date() - new Date(value.show_date + "," + value.show_time) <= 0) {
        tempMovieArr.push(value.movie_id);
      }
    });
    console.log(tempMovieArr);
    tempMovieArr2 = Array.from(new Set(tempMovieArr));
    let movieArray = [];
    let movieScheduleArray = [];
    tempMovieArr2.forEach(async value => {
      sql2 = "SELECT * FROM movie WHERE movie_id = ? LIMIT 1;";
      const result2 = await query(sql2, [value]);
      movieArray.push(result2[0]);

      sql3 =
        "SELECT * FROM schedule INNER JOIN movie ON schedule.movie_id = movie.movie_id WHERE schedule.movie_id = ? AND schedule.cinema_id = ?;";
      const result3 = await query(sql3, [value, cinemaId]);
      movieScheduleArray.push(result3);
    });
    setTimeout(() => {
      res.json({
        success_code: 200,
        data: {
          hasMovieInfo: movieArray,
          movieScheduleInfo: movieScheduleArray,
        },
      });
    }, 500);
  } catch (error) {}
};

//通过id加载当前影院详细信息
exports.getScheduleById = async (req, res) => {
  try {
    let { scheduleId } = req.query;
    let sqlStr = "SELECT * FROM schedule WHERE schedule_id = ? LIMIT 1;";
    const result = await query(sqlStr, [scheduleId]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "获取当前排片信息失败" });
    } else {
      res.json({ success_code: 200, data: result[0] });
    }
  } catch (error) {
    res.json({ error_code: 1, message: "排片信息不存在" });
  }
};

//更新座位信息
exports.updateScheduleSeat = async (req, res) => {
  try {
    let { scheduleId, seatInfo } = req.body;
    let sqlStr =
      "UPDATE schedule SET seat_info = ? WHERE schedule_id = ? LIMIT 1;";
    const result = await query(sqlStr, [seatInfo, scheduleId]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "更新排片座位信息失败" });
    } else {
      res.json({ success_code: 200, data: result[0] });
    }
  } catch (error) {
    res.json({ error_code: 1, message: "更新排片座位信息失败" });
  }
};

//某电影所有影院排片信息接口
exports.getCurrentMovieSchedule = async (req, res) => {
  try {
    let { movieId } = req.query;
    let sql = "SELECT * FROM schedule WHERE movie_id = ?;";
    const result = await query(sql, [movieId]);
    if (result.length == 0) {
      res.json({ error_code: 1, message: "获取当前影院排片信息失败" });
    } else {
      let tempDateArr = [];
      result.forEach(value => {
        if (
          new Date() - new Date(value.show_date + "," + value.show_time) <=
          0
        ) {
          tempDateArr.push(value.show_date);
        }
      });
      tempDateArr2 = Array.from(new Set(tempDateArr));
      tempDateArr2.sort((a, b) => {
        return new Date(a) - new Date(b);
      });
      let cinemaArray = [];
      let cinemaScheduleArray = [];
      tempDateArr.forEach(async value => {
        sql2 = "SELECT * FROM schedule WHERE show_date = ?";
        const result2 = await query(sql2, value);
        cinemaArray.push(result2);

        sql3 =
          "SELECT * FROM schedule INNER JOIN cinema ON schedule.cinema_id = cinema.cinema_id WHERE schedule.movie_id = ? AND schedule.show_date = ?;";

        const result3 = await query(sql3, [movieId, value]);
        cinemaScheduleArray.push(result3);
      });
      setTimeout(() => {
        res.json({
          success_code: 200,
          data: {
            hasCinemaInfo: cinemaArray,
            cinemaScheduleInfo: cinemaScheduleArray,
          },
        });
      }, 500);
    }
  } catch (error) {
    res.json({ error_code: 1, message: "排片信息不存在" });
  }
};

//根据名字匹配影院
exports.matchCinemaByName = async (req, res) => {
  try {
    let { cinemaName } = req.query;
    let sqlStr =
      "SELECT * FROM schedule INNER JOIN cinema ON schedule.cinema_id = cinema.cinema_id INNER JOIN movie ON schedule.movie_id = movie.movie_id WHERE cinema_name LIKE ?;";
    const result = await query(sqlStr, ["%" + cinemaName + "%"]);
    if (result.length == 0) {
      console.log(error);
      res.json({ error_code: 1, message: "error" });
    } else {
      if (result.length) {
        result = result.filter(value => {
          return (
            new Date(value.show_date + "," + value.show_time) - new Date() > 0
          );
        });
        for (let i = 0; i < result.length; i++) {
          for (let j = i + 1; j < result.length; j++) {
            if (result[i]["cinema_id"] === result[j]["cinema_id"]) {
              result.splice(j, 1);
              j = j - 1;
            }
          }
        }
        res.json({ success_code: 200, data: result });
      }
    }
  } catch (error) {
    res.json({ error_code: 1, message: "error" });
  }
};
